package com.basin.common.mybatisflex.listener;

import com.basin.common.mybatisflex.base.BaseEntity;
import com.basin.common.satoken.support.BasinAuthTool;
import com.mybatisflex.annotation.InsertListener;
import com.mybatisflex.annotation.UpdateListener;

import java.sql.Timestamp;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 * @date: 2025/4/6 21:02
 * @description:
 */
public class InsertOrUpdateListener implements InsertListener, UpdateListener {
    @Override
    public void onInsert(Object o) {
        if (o instanceof BaseEntity entity) {
            // 时间
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            entity.setCreateTime(timestamp);
            entity.setUpdateTime(timestamp);
            // 用户
            String loginId = BasinAuthTool.getLoginId();
            entity.setCreateUser(loginId);
            entity.setUpdateUser(loginId);
            // 租户
            String tenantId = BasinAuthTool.getTenantId();
            entity.setTenantId(tenantId);
        }
    }

    @Override
    public void onUpdate(Object o) {
        if (o instanceof BaseEntity entity) {
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            entity.setUpdateTime(timestamp);
            String loginId = BasinAuthTool.getLoginId();
            entity.setUpdateUser(loginId);
        }
    }
}
